const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const { exec } = require('child_process');

function createWindow() {
  const win = new BrowserWindow({
    width: 900,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true
    }
  });
  win.loadFile('index.html');
}

app.whenReady().then(() => {
  createWindow();
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

// 获取所有磁盘信息（PowerShell）
ipcMain.handle('get-disks', async () => {
  return new Promise((resolve) => {
    exec('powershell -Command "Get-PhysicalDisk | Select-Object FriendlyName,DeviceId,MediaType,OperationalStatus,Size | ConvertTo-Json"', (err, stdout) => {
      if (err) return resolve([]);
      try {
        const disks = JSON.parse(stdout);
        resolve(Array.isArray(disks) ? disks : [disks]);
      } catch {
        resolve([]);
      }
    });
  });
});

// 批量脱机操作
ipcMain.handle('offline-disks', async (event, deviceIds) => {
  return new Promise((resolve) => {
    const script = deviceIds.map(id => `Set-Disk -Number ${id} -IsOffline $true`).join('; ');
    exec(`powershell -Command "${script}"`, (err) => {
      resolve(!err);
    });
  });
});
